﻿using System.ComponentModel.DataAnnotations;
using System.Text;

using HttpClientStudy.WebApp.Models;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace HttpClientStudy.WebApp.Controllers
{
    /// <summary>
    /// 高级Get请求 控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AdvancedGetController : ControllerBase
    {
        private ILogger<SimpleController> _logger;

        /// <summary>
        /// 构造
        /// </summary>
        public AdvancedGetController(ILogger<SimpleController> logger)
        { 
            _logger = logger;
        }

        /// <summary>
        /// GET请求接口
        /// 携带请求正文：接口内直接读取Request.Body流
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWithBody()
        {
            if (Request.Body == null)
            { 
                return new JsonResult(BaseResultUtil.Fail("没有请求体"));
            }

            if (Request.ContentLength <= 0)
            {
                return new JsonResult(BaseResultUtil.Fail("请求体中没有数据"));
            }

            using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))
            {
                var requestBody = await reader.ReadToEndAsync();

                //有关于请求体的业务逻辑

                var result = BaseResultUtil.Success(requestBody);
                return Ok(result);
            }
        }

        /// <summary>
        /// GET请求接口
        /// 携带请求正文：使用模型绑定
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWithFormBody([FromForm] int Id,[FromForm] string name)
        {
            AdvancedGetModel vm = new AdvancedGetModel() { Id = Id, Name = name };
            var result = BaseResultUtil.Success(vm);

            await Task.CompletedTask;

            return Ok(result);
        }

        /// <summary>
        /// GET请求接口
        /// 携带请求正文：使用模型绑定
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWithJsonBody([FromBody] AdvancedGetModel vm)
        {
            var result = BaseResultUtil.Success(vm);

            await Task.CompletedTask;

            return Ok(result);
        }

        /// <summary>
        /// 接收带请求体数据的Get请求
        /// 携带请求正文：模型绑定后 + 读取Request.Body流(复制流方式)
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWithBodyByCopyStream([FromBody] AdvancedGetModel vm)
        {
            if (Request.Body == null)
            {
                return new JsonResult(BaseResultUtil.Fail("没有请求体"));
            }

            if (Request.ContentLength <= 0)
            {
                return new JsonResult(BaseResultUtil.Fail("请求体中没有数据"));
            }

            /* 
             * 复制流方式 
             */

            // 创建一个内存流存储请求体
            using (var memStream = new MemoryStream())
            {
                // 复制请求体到内存流
                await HttpContext.Request.Body.CopyToAsync(memStream);

                // 重置内存流的位置，以便从头开始读取
                memStream.Seek(0, SeekOrigin.Begin);

                // 从内存流中读取文本内容
                using (var reader = new StreamReader(memStream))
                {
                    var requestBody = await reader.ReadToEndAsync();
                    // 现在你可以按照你的需要使用requestBody字符串
                    // 例如，将其作为响应返回

                    var result = BaseResultUtil.Success(requestBody);
                    return Ok(result);
                }
            }
        }

        /// <summary>
        /// 接收带请求体数据的Get请求
        /// 携带请求正文：模型绑定后 + 读取Request.Body流(启用倒带功能-推荐)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetWithBodyByEnableBuffering([FromBody] AdvancedGetModel vm)
        {
            if (Request.Body == null)
            {
                return new JsonResult(BaseResultUtil.Fail("没有请求体"));
            }

            if (Request.ContentLength <= 0)
            {
                return new JsonResult(BaseResultUtil.Fail("请求体中没有数据"));
            }

            /*
             * 启用倒带功能,读取Request.Body流
             * .net core 2.0 
             * Request.EnableRewind(); 
             *
             * .net core 3+
             * Request.EnableBuffering();
             */

            Request.EnableBuffering();
            Request.Body.Position = 0;

            using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))
            {
                var requestBody = await reader.ReadToEndAsync();

                var result = BaseResultUtil.Success(requestBody);
                return Ok(result);
            }
        }

        /// <summary>
        /// Post 测试方法
        /// 表单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostFormData([FromForm,Required]int Id, [FromForm,Required]string name)
        {
            var paras = $"{nameof(Id)}={Id}&{nameof(name)}={name}";
            var result = BaseResultUtil.Success(paras);
            return Ok(result);
        }

        /// <summary>
        /// Post 测试方法
        /// json 数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostJsonData([FromBody]AdvancedGetModel? vm)
        {
            var result = BaseResultUtil.Success(vm);
            return Ok(result);
        }
    }
}
